package com.jiazhuo.blockgamesquare.http.callback

import android.text.TextUtils
import com.jiazhuo.blockgamesquare.bean.BaseBean
import com.jiazhuo.blockgamesquare.util.toast
import io.reactivex.observers.DisposableObserver


/**
 *
 * @author Administrator
 * @time 2018/8/22 10:14
 */

abstract class BaseObserver<T> : DisposableObserver<BaseBean<T>>() {

    override fun onStart() {
    }

    override fun onNext(tBaseBean: BaseBean<T>) {
        if (tBaseBean.code == 0) {
            try {
                if (!TextUtils.isEmpty(tBaseBean.msg) && !tBaseBean.msg?.contains("upToken")!!){
                    toast(tBaseBean.msg)
                }
                success(tBaseBean.data)
            } catch (e: Exception) {
                println("onNext: " + e.toString())
                e.printStackTrace()
                onError(e)
            }
            println("onNext: " + " code -> " + tBaseBean.code + " msg -> " + tBaseBean.msg)
        } else {
            val customException = CustomException(tBaseBean.code, tBaseBean.msg)
            toast(tBaseBean.msg)
            println(customException.toString())
            fail(customException)
            if (tBaseBean.code == ErrorCode.TOKEN_INVALIDE) {
                //token失效，重新登录
                reLogin()
            }
        }
    }

    /**
     * 重新登录
     */
    private fun reLogin() {
    }


    override fun onError(e: Throwable) {
        val customException = CustomException(e)
        toast(customException.toString())
        fail(customException)
    }

    override fun onComplete() {
    }

    abstract fun success(data: T?)

    abstract fun fail(e: CustomException)

}
